package com.itheima.reggie.service.impl;

import java.time.LocalDateTime;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.utils.UUIDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


@Service
public class OrderServiceImpl implements OrderService {
    @Autowired(required = false)
    private OrderMapper orderMapper;
    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;


    /**
     * 作用:下单
     *
     * @param orders
     * @param userId
     * @return
     */
    @Override
    public void submit(Orders orders, Long userId) {
        //A. 获得当前用户id, 查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findShoppingCartByUserId(userId);
        //B. 根据当前登录用户id, 查询用户数据
        User user = userMapper.findById(userId);
        //C. 根据地址ID, 查询地址数据
        final AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
        //订单的id
        final Long orderId = UUIDUtils.getUUIDInOrderId().longValue();
        // 声明变量记录总金额
        BigDecimal totalAmount = new BigDecimal("0");
        //D. 遍历所有的购物像， 一个购物项就是一个订单明细， 组装订单明细数据, 批量保存订单明细
        final ArrayList<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            final OrderDetail orderDetail = new OrderDetail();
            orderDetail.setId(UUIDUtils.getUUIDInOrderId().longValue());  //主键
            orderDetail.setName(shoppingCart.getName());   //购物项菜品名字
            orderDetail.setOrderId(orderId);   //订单项所属的订单id
            orderDetail.setDishId(shoppingCart.getDishId());    //订单项所属的菜品id
            orderDetail.setSetmealId(shoppingCart.getSetmealId());  //订单项所属的套餐id
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor()); //订单项口味id
            orderDetail.setNumber(shoppingCart.getNumber());  //数量
            orderDetail.setAmount(shoppingCart.getAmount());  //订单单价
            orderDetail.setImage(shoppingCart.getImage());    //图片
            //计算每一个购物项的总价
            BigDecimal bigDecimal = new BigDecimal(shoppingCart.getNumber() + "");
            BigDecimal amount = shoppingCart.getAmount().multiply(bigDecimal);
            totalAmount = totalAmount.add(amount);
            orderDetailList.add(orderDetail);
        }
        //E. 组装订单数据, 批量保存订单数据
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setStatus(1);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(0);
        orders.setAmount(totalAmount);
        orders.setRemark(orders.getRemark());
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        //插入订单
        orderMapper.save(orders);
        //批量插入订单
        orderDetailMapper.saveBath(orderDetailList);
        //F. 删除当前用户的购物车列表数据
        shoppingCartMapper.clean(userId);
    }

    @Override
    public PageBean<OrdersDto> userPage(Integer page, Integer pageSize) {
        //1. 设置当前页鱼页面大小
        PageHelper.startPage(page, pageSize);
        //2. 查询数据
        List<OrdersDto> orderList = orderMapper.findById(page, pageSize);
        for (OrdersDto ordersDto : orderList) {
            ordersDto.setOrderDetails(orderDetailMapper.findById(ordersDto.getId()));
            BeanUtils.copyProperties(ordersDto, orderList);


        }

        PageInfo<OrdersDto> pageInfo = new PageInfo<>(orderList);
        PageBean<OrdersDto> pageResult = new PageBean<>(pageInfo.getList(), pageInfo.getTotal(), pageInfo.getPageSize(), pageInfo.getPageNum(), pageInfo.getPages());
        return pageResult;
    }

    @Override
    public Page<Orders> findByNumberAndTime(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        //1. 设置当前页和页面大小
        PageHelper.startPage(page, pageSize);
        //2. 查找页面数据
        List<Orders> ordersList = orderMapper.findByNumberAndTime(number, beginTime, endTime);
        //创建PageInfo对象,将List集合传入
        final PageInfo<Orders> ordersPageInfo = new PageInfo<>(ordersList);
        //4. 把padinIfo放进Page
        Page<Orders> pageResult = new Page<>(ordersPageInfo.getList(), ordersPageInfo.getTotal(), ordersPageInfo.getPageSize(), ordersPageInfo.getPageNum());
        return pageResult;

    }

    @Override
    public void again(Orders orders , Long userId) {
        /**
         * 再来一单
         * @param id
         */
        shoppingCartMapper.clean(userId);
        //将当前的菜品放进购物车
        List<OrderDetail> orderDetails = orderDetailMapper.findById(orders.getId());
        System.out.println("orderDetails = " + orderDetails+"============================================");
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setName(orderDetail.getName());
            shoppingCart.setImage(orderDetail.getImage());
            shoppingCart.setUserId(userId);
            shoppingCart.setDishId(orderDetail.getDishId());
            shoppingCart.setSetmealId(orderDetail.getSetmealId());
            shoppingCart.setDishFlavor(orderDetail.getDishFlavor());
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCart.setAmount(orderDetail.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            System.out.println("shoppingCart = " + shoppingCart);
            shoppingCartMapper.save(shoppingCart);
        }
    }


}
